import 'package:baselib/base/app_channel.dart';
import 'package:baselib/util/shared_preferences_util.dart';
import 'package:dio/dio.dart';

class HttpUtil{

  static HttpUtil instance;
  Dio dio;
  BaseOptions options;

  static HttpUtil getInstance() {
    if (instance == null) {
      instance = new HttpUtil();
    }
    return instance;
  }
  HttpUtil() {
    _initDio();
  }


  _initDio()  {

    String baseRequestUrl=Channel.baseURL;
    dio = new Dio()
      ..options = BaseOptions(
          baseUrl: baseRequestUrl,
          connectTimeout: 15000,
          receiveTimeout: 15000)
      ..interceptors.add(HeaderInterceptor())
      ..interceptors.add(LogInterceptor(responseBody: true, requestBody: true));
  }
}

class HeaderInterceptor extends Interceptor  {
  HeaderInterceptor();
  @override
  onRequest(RequestOptions options) {
    final String token = SharedPreferencesUtils().getToken();
    if (token != null && token.length > 0) {
      options.headers.putIfAbsent('Authorization', () => 'Bearer' + ' ' + token??"");
    }
    return super.onRequest(options);
  }
}